/*********************************************************************
 * Módulo 3. Tutorial de desarrollo con NME. Mini-Juego: Bee Adventures 
 * Programación Multimedia y Juegos
 * Autor: David Vallejo Fernández    david.vallejo@tegnix.com
 * Autor: Carlos González Morcillo   carlos.gonzalez@tegnix.com
 *
 * You can redistribute and/or modify this file under the terms of the
 * GNU General Public License ad published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * and later version. See <http://www.gnu.org/licenses/>.
 *
 * This file is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.  
 *********************************************************************/

package;

import util.FpsLabel;
import util.ScoreBoard;
import graphics.sprites.SimpleOverlay;
import graphics.ParallaxManager;
import graphics.ActorManager;
import sound.SoundManager;

import aze.display.TileLayer;
import aze.display.TileSprite;
import aze.display.SparrowTilesheet;
import nme.Assets;
import nme.display.Sprite;
import nme.events.Event;
import nme.events.KeyboardEvent;
import nme.events.MouseEvent;
import nme.ui.Keyboard;
import nme.Lib;
import nme.geom.Rectangle;

class BeeGame extends Sprite {

	var _overlay:SimpleOverlay;           // Imagen del marcador
	var _speaker:SimpleOverlay;           // Imagen del altavoz
	var _muted_speaker:SimpleOverlay;     // Imagen del altavoz silenciado
	var _scoreBoard:ScoreBoard;           // Actualiza los puntos
	var _fpsText:FpsLabel;                // Muestra los FPS
	var _parallaxManager:ParallaxManager; // Scroll Manager
	var _actorManager:ActorManager;       // Manager de Actores

	var _layer:TileLayer;                 // Capa Pcpal. de dibujado
	var _previousTime:Int;                // Para calcular Delta(t)

	// Constructor =====================================================
	public function new() {
		super(); haxe.Timer.delay(init, 150);
	}
	
	function init():Void {
		createScene();
		addListeners();
		_previousTime = Lib.getTimer();
		loadMusic();
	}

	// Carga de Recursos ===============================================
	function loadAssets():Void{
		var sheetData:String = Assets.getText("assets/bee.xml");
		var tilesheet:SparrowTilesheet = new SparrowTilesheet(Assets.getBitmapData("assets/bee.png"), sheetData);
		_layer = new TileLayer(tilesheet);
		addChild(_layer.view);
	}

	// Creación de la Escena ===========================================
	function createScene():Void {
		loadAssets();

		_parallaxManager = new ParallaxManager(_layer);
		_parallaxManager.addSky("sky");
		_parallaxManager.addBackgroundStrip("2cloud2", 10, 1.7, 300, -5);
		_parallaxManager.addBackgroundStrip("2cloud1", 10, 2, 320, 10);
		_parallaxManager.addBackgroundStrip("trees", 4, 1, 220, 40);
		_parallaxManager.addBackgroundStrip("sheeps", 4, 1, 160, 140);
		_parallaxManager.addBackgroundStrip("clouds", 4, 1.3, 280, 80);
		_parallaxManager.addBackgroundStrip("flowers", 4, 1, 70, 300);

		_overlay = new SimpleOverlay("scoreboard", 70, 75); 
		_speaker = new SimpleOverlay("speaker", 175, 50); 
		_muted_speaker = new SimpleOverlay("muted_speaker", 175, 50); 
		_muted_speaker.visible = false;
		_scoreBoard = new ScoreBoard(20,20,0xff0000,"assets/margarosa.ttf");
		_fpsText = new FpsLabel(25, 110, 0x606060, "assets/cafeta.ttf");  
		_layer.addChild(_overlay); _layer.addChild(_speaker); _layer.addChild(_muted_speaker);
		addChild(_scoreBoard); addChild(_fpsText);
  
		_actorManager = new ActorManager(_layer, stage.stageWidth, stage.stageHeight, _scoreBoard);

		_actorManager.addPlayer("bee");
	}

	// Bucle Principal =================================================
	function mainLoop(eTime:Int):Void {
		_fpsText.update();
		_parallaxManager.update(stage.stageWidth, stage.stageHeight, eTime);
		_actorManager.update(stage.stageWidth, stage.stageHeight, eTime);
		_layer.render();
	}

	// Listeners =======================================================
	function addListeners():Void {
		stage.addEventListener(Event.ENTER_FRAME, onEnterFrame);
		stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPressed);
		stage.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
		stage.addEventListener(MouseEvent.CLICK, onMouseClicked);
	}

	function onKeyPressed(event:KeyboardEvent):Void {
		switch (event.keyCode) {

			case Keyboard.DOWN:
				SoundManager.getInstance().turnVolumeDown();
			case Keyboard.UP:
				SoundManager.getInstance().turnVolumeUp();
			case Keyboard.RIGHT:
				SoundManager.getInstance().increaseRightBalance();
			case Keyboard.LEFT:
				SoundManager.getInstance().increaseLeftBalance();

			case 109: // Tecla 'm'
				mute_unmute();

			default:
				_actorManager.onKeyPressed(event);
	}
}
 
	function onMouseMove(event:MouseEvent):Void {
		_actorManager.onMouseMove(event);
	}

	// Para activar/desactivar el sonido.
	function onMouseClicked (event:MouseEvent):Void {
		// Delega en Rectangle.
		var rectangle:Rectangle = new Rectangle(_speaker.x - _speaker.width / 2, _speaker.y - _speaker.height / 2, _speaker.width, _speaker.height);

		if (rectangle.contains(event.localX, event.localY)) {
			mute_unmute();
		}
	}

	function onEnterFrame(event:Event):Void {
		var now = Lib.getTimer();
		var elapsedTime = now - _previousTime;
		_previousTime = now;
		mainLoop(elapsedTime);
	}

	// Music ===========================================================
	private function loadMusic () {
		SoundManager.getInstance().loadBackgroundMusic("assets/stars.mp3");
		SoundManager.getInstance().playBackgroundMusic();
	}

	// Comprueba si el sonido estaba activado o no,
	// y activa/desactiva overlays de iconos de sonido.
	private function mute_unmute () : Void {
		if (SoundManager.getInstance().isMuted()) {
			_muted_speaker.visible = false;
			_speaker.visible = true;
			SoundManager.getInstance().unmute();
		} else {
			_speaker.visible = false;
			_muted_speaker.visible = true;
			SoundManager.getInstance().mute();
		}
	}

	// Main ============================================================  
	static public function main() {
		Lib.current.addChild(new BeeGame());
	}
}
